import asyncio
from pprint import pprint
import pymysql
from common.constant import *
from loguru import logger
from dbutils.pooled_db import PooledDB
import aiomysql


class CursorHandler:
    # hasinstance = False
    # instance = None

    # def __new__(cls, *args, **kwargs):
    #     if cls.hasinstance:
    #         return cls.instance
    #     print('connect to database...')
    #     # 协程的标准操作：获取事件异步轮询事件对象
    #     newloop = asyncio.new_event_loop()
    #     asyncio.set_event_loop(newloop)
    #     loop = asyncio.get_event_loop()
    #     # 调用异步包中协程代理线程：运行协程线程——事件，丢给协程轮询线程
    #     asyncio.run_coroutine_threadsafe(CursorHandler.make_connect(), loop)
    #     # 手动调用初始化对象
    #     cls.instance = object.__new__(cls)
    #     cls.hasinstance = True
    #     return cls.instance

    def __init__(self):
        self.make_connect()

    def make_connect(self):
        try:
            self.db = aiomysql.create_pool(
                host=mysql_ip,  # 服务端地址
                port=mysql_port,  # 服务端端口
                maxsize=1000,
                minsize=100,
                user=mysql_user,  # 用户名
                password=mysql_password,  # 密码
                db=mysql_database,  # 要连接的数据库
                charset='utf8'  # 设置数据库编码
                # cursorclass=pymysql.cursors.DictCursor # 以字典的方式返回结果
                                   )
            self.db.acquire()
        except Exception as e:
            print('mysql make connect error')
            logger.error(e)

        return self.db


    def make_cursor(self):
        try:
            # 构造游标
            self.cursor = self.db.cursor()
        except IOError:
            print('msyql_cursor make error')
            logger.error('msyql_cursor make error')
            self.make_cursor()
        except Exception as e:
            print('mysql other error')
            logger.error(e)
            exit(1)
            self.make_cursor()
        return self.cursor

    def close_database(self):
        # 关闭数据库连接
        self.db.close()

    def search_with_condition(self, sql, condition):
        # 待查询条件的搜索
        sql.format(*condition)
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    async def search_alone(self, sql=''):
        # 查询数据库的执行语句
        # sql = 'select * from zt_acl limit 10'
        try:
            self.make_cursor()
            await self.cursor.execute(sql)
            self.cursor.close()
        except Exception as e:
            print(e)
            self.__init__()
            await self.cursor.execute(sql)
        return await self.cursor.fetchall()

cursor = CursorHandler()



